<template>
  <page-layout class="demand">
    <div class="search-wrapper">
      <div>
        <a-input
          placeholder="请输入需求名称"
          class="search-input"
          v-model="searchText"
        >
          <a-icon
            slot="prefix"
            type="search"
            style="font-size: 28px; color: #999"
          />
        </a-input>
        <a-button type="primary" @click="handelsearch" class="search-button"
          >搜索</a-button
        >
      </div>
      <a-button
        v-if="userInfo.permissions.requirements_insert"
        style="width: 120px; height: 54px"
        type="primary"
        @click="
          $router.push({
            path: '/demand/add',
            query: { random: random }
          })
        "
      >
        新增
      </a-button>
    </div>

    <!-- <a-card> -->
    <div class="tabel-wrapper">
      <!-- <div class="operator">
          <a-button @click="addNew" type="primary">新建</a-button>
          <a-button>批量操作</a-button>
          <a-dropdown>
            <a-menu @click="handleMenuClick" slot="overlay">
              <a-menu-item key="delete">删除</a-menu-item>
              <a-menu-item key="audit">审批</a-menu-item>
            </a-menu>
            <a-button> 更多操作 <a-icon type="down" /> </a-button>
          </a-dropdown>
        </div> -->
      <standard-table
        :columns="columns"
        :dataSource="dataSource"
        @change="onChange"
        :pagination="pagination"
        size="large"
        :loading="loading"
      >
        <div slot="status" slot-scope="{ text }">
          <!-- {{ text }}
          {{ demandStatus }} -->
          <a-tag
            :style="`
              width: 70px;
              height: 30px;
              text-align: center;
              line-height: 30px;
            `"
            :color="demandStatus[text ? text - 1 : 0].color"
          >
            {{ demandStatus[text ? text - 1 : 0].text }}
          </a-tag>
        </div>
        <!-- eslint-disable-next-line -->
        <!-- 需求调研 -->
        <div slot="process" slot-scope="{ text, record }">
          <!-- {{ record }} -->
          <a
            v-if="record.is_surveys === 1"
            :href="`#/demand/surveyDetail?random=${random}&&id=${record.key}`"
          >
            详情 |
          </a>
          <a
            v-if="
              record.is_surveys === 1 &&
              userInfo.permissions.requirements_surveyedit
            "
            :href="`#/demand/surveyAdd?random=${random}&&id=${record.key}`"
          >
            编辑
          </a>
          <a disabled v-if="record.is_surveys === 0" href="javascript:;">
            暂无
          </a>
          <!-- {{ record.is_surveys }} -->
          <a
            v-if="
              record.is_surveys === 0 &&
              userInfo.permissions.requirements_surveyinsert
            "
            :href="`#/demand/surveyAdd?random=${random}&&id=${record.key}&&is_surveys=${record.is_surveys}`"
          >
            | 添加
          </a>
        </div>
        <!-- eslint-disable-next-line -->
        <div slot="changes" slot-scope="{ record }">
          <template>
            <a
              style="text-decoration: underline"
              @click="change_infos(record.key)"
              title="点击查看需求变更记录"
            >
              查看变更记录
            </a>
          </template>
        </div>
        <div slot="tasks" slot-scope="{ record }">
          <template>
            <a
              style="text-decoration: underline"
              @click="task_infos(record.key)"
              title="查看该需求下的任务的执行情况"
            >
              任务记录
            </a>
          </template>
        </div>
        <!-- 操作栏 -->
        <div slot="action" slot-scope="{ record }">
          <a
            v-if="
              record.status <= 4 && userInfo.permissions.requirements_detail
            "
            :href="`#/demand/detail?random=${random}&&id=${record.key}`"
            style="margin-right: 8px"
            >详情
          </a>
          <a
            v-else
            :href="`#/demand/detail?random=${random}&&id=${record.key}&&finish=1`"
            style="margin-right: 8px"
            >详情
          </a>
          <template>
            <a
              v-if="userInfo.permissions.requirements_edit"
              :href="`#/demand/add?random=${random}&&id=${record.key}`"
              style="margin-right: 8px"
              >| 编辑
            </a>
            <a-popconfirm
              v-if="userInfo.permissions.requirements_delete"
              title="确定删除此条需求吗?"
              ok-text="是的"
              cancel-text="取消"
              @confirm="() => delete_confirm(record.key)"
              @cancel="() => cancel(record.key)"
            >
              <a>| 删除 </a>
            </a-popconfirm>
            <a
              v-if="userInfo.permissions.task_insert"
              :href="`#/task/add?random=${random}&&demand_id=${record.key}`"
              style="margin-right: 8px"
              >| 发任务</a
            >
            <a-dropdown v-if="userInfo.permissions.requirements_suspend">
              <a class="ant-dropdown-link" @click="(e) => e.preventDefault()">
                | 审核 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item v-if="record.status < 2">
                  <a-popconfirm title="确认通过需求?" @confirm="() =>handelStatusChange(2, record.key)">
                      <a href="javascript:;" style="color: blue">通过需求</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item >
                  <a-popconfirm title="确认中止需求?" @confirm="() =>handelStatusChange(5, record.key)">
                      <a href="javascript:;" style="color: red">中止需求</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </div>
        <template slot="statusTitle">
          <a-icon @click.native="onStatusTitleClick" type="info-circle" />
        </template>
      </standard-table>
    </div>
    <!-- </a-card> -->
    <a-modal
      :footer="null"
      :destroyOnClose="true"
      v-model="changes_visible"
      title="变更记录"
      ok-text="确认"
      @ok="hideModal"
      @cancel="hideModal"
      width="580px"
    >
      <a-table bordered :data-source="change_datas" :columns="change_columns">
        <div slot="content" slot-scope="content" v-html="content"></div>
        <template
          slot="change_status"
          slot-scope="change_status, change_message"
          v-if="userInfo.permissions.requirements_suspend"
        >
          <a-popconfirm
            v-if="change_status == 1"
            title="确认审核通过?"
            @confirm="
              () =>
                confirmChangeStatus(
                  change_message.id,
                  2,
                  change_message.requirement_id
                )
            "
          >
            <a href="javascript:;">
              <p style="text-decoration: underline; color: green">通过</p></a
            >
          </a-popconfirm>
          <a-popconfirm
            v-if="change_status == 1"
            title="确认中止该变更?"
            @confirm="
              () =>
                confirmChangeStatus(
                  change_message.id,
                  3,
                  change_message.requirement_id
                )
            "
          >
            <a href="javascript:;" style="">
              <p style="text-decoration: underline; color: red">中止</p></a
            >
          </a-popconfirm>
          <a v-if="change_status != 1">
            <a
              href="javascript:;"
              style="color: "
              v-if="change_message.status == 2"
              >已审核</a
            >
            <a
              href="javascript:;"
              style="color: gray"
              v-if="change_message.status == 3"
              >已中止</a
            >
          </a>
        </template>
        <template slot="files" slot-scope="files">
          <a v-if="!files || files.length === 0">暂无附件</a>

          <!-- <div  class="enclosure-wrapper"> -->
          <div v-else class="enclosure-wrapper">
            <div
              class="enclosure-item"
              v-for="file in JSON.parse(files)"
              :key="file.uid"
            >
              <a-icon type="file-zip" theme="twoTone" style="font-size: 50px" />
              <a
                :href="
                  file.response && file.response.data && file.response.data.url
                "
                download:void
                class="enclosure-content"
                >{{ file.name }}</a
              >
            </div>
          </div>
        </template>
        <template
          slot="operation"
          slot-scope="change_message"
          v-if="userInfo.permissions.task_insert"
        >
          <!-- <template v-if="record.examiner_id === userId || record.confirmation_id === userId">  -->
          <template>
            <a
              v-if="change_message.status == 2"
              :href="`#/task/add?random=${random}&&demand_id=${change_message.requirement_id}&&change_id=${change_message.id}`"
              style="margin-right: 8px"
              @click="hideModal()"
            >
              发任务
            </a>
            <a v-else href="javascript:;" style="color: gray">发任务</a>
          </template>
        </template>
      </a-table>
    </a-modal>
    <a-modal
      :footer="null"
      :destroyOnClose="true"
      v-model="task_visible"
      title="任务记录"
      ok-text="确认"
      @ok="hideModal"
      @cancel="hideModal"
      width="580px"
    >
      <a-table bordered :data-source="tasks_data" :columns="task_columns">
        <template slot="haha" slot-scope="text, record">
          <a
            :href="`#/task/detail?random=${random}&&id=${record.task_id}`"
            @click="hideModal"
          >
            {{ text }}</a
          >
        </template>
      </a-table>
    </a-modal>
  </page-layout>
</template>

<script>
import PageLayout from "@/layouts/PageLayout";
import Cookie from "js-cookie";
import StandardTable from "@/components/table/StandardTable";
import {
  list,
  deleteItem,
  suspend,
  changes,
  changeStatus,
  tasks
} from "@/services/demand";
import LoginVue from "../login/Login.vue";
// import { mapMutations } from "vuex";
const columns = [
  {
    title: "ID",
    dataIndex: "key",
    key: "id"
    // sorter: true
  },
  {
    title: "所属部门",
    dataIndex: "department",
    key: "department"
  },
  {
    title: "需求名称",
    dataIndex: "title",
    key: "title"
  },
  {
    title: "需求方",
    dataIndex: "author",
    key: "author"
  },
  {
    title: "负责人",
    dataIndex: "principal",
    key: "principal"
  },
  {
    title: "关联项目",
    dataIndex: "project",
    key: "project"
  },
  {
    title: "关联产品",
    dataIndex: "produce",
    key: "produce"
  },
  {
    title: "关联任务",
    scopedSlots: { customRender: "tasks" }
  },
  {
    title: "审核状态",
    dataIndex: "status",
    key: "status",
    scopedSlots: { customRender: "status" }
  },
  {
    title: "需求调研",
    dataIndex: "is_surveys",
    key: "is_surveys",
    scopedSlots: { customRender: "process" }
  },
  {
    title: "需求变更",
    scopedSlots: { customRender: "changes" }
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
    align: "center"
  }
];
const change_columns = [
  {
    title: "id",
    dataIndex: "id",
    scopedSlots: { customRender: "key" },
    key: "id",
    width: 55
    //   scopedSlots: { customRender: 'name' },
  },
  {
    title: "备注内容",
    dataIndex: "content",
    scopedSlots: { customRender: "content" },
    key: "content"
  },
  {
    title: "附件",
    dataIndex: "files",
    key: "files",
    scopedSlots: { customRender: "files" }
  },
  {
    title: "提交时间",
    dataIndex: "created_at",
    key: "created_at",
    ellipsis: true
  },
  {
    title: "审核状态",
    dataIndex: "status",
    scopedSlots: { customRender: "change_status" },
    align: "center"
  },
  {
    title: "操作",
    scopedSlots: { customRender: "operation" },
    align: "center"
  }
];
const task_columns = [
  {
    title: "ID",
    dataIndex: "task_id",
    scopedSlots: { customRender: "key" },
    key: "id",
    width: 55
    //   scopedSlots: { customRender: 'name' },
  },
  {
    title: "任务名称",
    dataIndex: "title",
    scopedSlots: { customRender: "haha" },
    key: "title"
  },
  {
    title: "工程师",
    dataIndex: "engineer",
    key: "engineer_id"
    // scopedSlots: { customRender: "files" },
  },
  {
    title: "开始时间",
    dataIndex: "started_at",
    key: "started_at"
    // ellipsis: true,
  },
  {
    title: "当前状态",
    dataIndex: "status",
    // scopedSlots: { customRender: "statu" },
    key: "status",
    align: "center"
  }
];
export default {
  name: "demand",
  components: { PageLayout, StandardTable },
  data() {
    return {
      userInfo: [],
      task_visible: false,
      changes_visible: false,
      change_datas: "",
      tasks_data: "",
      userId: "",
      random: "",
      task_columns,
      change_columns,
      loading: true,
      searchText: "",
      desc: "需求管理中心",
      advanced: true,
      columns: columns,
      dataSource: [],
      selectedRows: [],
      pagination: {
        size: "small",
        showSizeChanger: true,
        showQuickJumper: true,
        poposition: "bottom",
        pageSize: 5,
        current: 1,
        total: 0
      },
      demandStatus: [
        {
          color: "#2591FF",
          text: "待审核"
        },
        {
          color: "#4E25FF",
          text: "排期中"
        },
        {
          color: "#FF6D25",
          text: "处理中"
        },
        {
          color: "yellowgreen",
          text: "待验收"
        }
      ]
    };
  },
  authorize: {
    deleteRecord: "delete"
  },
  activated() {
    const { pageSize, current } = this.pagination;
    this.random = Math.random();
    this.loadTableData({ limit: pageSize, page: current });
  },
  created() {
    let userInfo = JSON.parse(window.localStorage.getItem("admin.user"));
    this.userInfo = userInfo;
    // 初始数据
    this.random = Math.random();
    const { pageSize, current } = this.pagination;
    this.loadTableData({ limit: pageSize, page: current });
  },
  mounted() {
    this.userId = +Cookie.get("Authorization").split(" ")[1];
    // console.log(typeof this.userId);
  },
  methods: {
    task_infos(id) {
      this.getTasks(id);
      this.task_visible = true;
      // console.log(this.tasks_data)  //这个打印会报错
      //  console.log(id)
    },
    //获取变更数据
    getTasks(id) {
      tasks(id).then((res) => {
        if (res.data.code === 20000) {
          this.tasks_data = res.data.data;
          console.log(res.data);
          // this.$message.success(res.data.message);
        }
      });
    },
    //修改需求变更的状态
    confirmChangeStatus(change_id, status, requirement_id) {
      // console.log(change_id)
      // alert(change_id)
      changeStatus({ change_id, status }).then((res) => {
        // console.log(res);
        if (res.data.code === 20000) {
          this.getChanges(requirement_id);
        }
      });
    },
    //打开弹窗，展示(需求变更)数据
    change_infos(id) {
      this.getChanges(id);
      this.changes_visible = true;
    },
    //获取变更数据
    getChanges(id) {
      changes(id).then((res) => {
        if (res.data.code === 20000) {
          this.change_datas = res.data.data;
          // this.$message.success(res.data.message);
        }
      });
    },
    hideModal(a) {
      this.change_datas = null;
      this.changes_visible = false;
      this.task_visible = false;
      this.tasks_data = null;
    },
    // 请求table 的数据
    // obj 请求的字段
    loadTableData(obj) {
      this.loading = true;
      list(obj).then((res) => {
        // 关闭loading
        this.loading = false;
        if (res.data.code === 20000) {
          // eslint-disable-next-line no-unused-vars
          const { current_page, total, per_page } = res.data.data;
          Object.assign(this.pagination, {
            total: parseInt(total),
            current: parseInt(current_page),
            pageSize: parseInt(per_page)
          });
          this.dataSource = res.data.data.data.map((item) => {
            const {
              department,
              requirement_id,
              created_at,
              title,
              author,
              project,
              produce,
              status,
              examiner,
              is_surveys,
              principal
            } = item;
            return {
              key: requirement_id,
              created_at: created_at && created_at.split(" ")[0],
              title: title || "未知",
              author: author || "未知",
              project: project || "无关联项目",
              status,
              produce: produce || "无关联产品",
              examiner,
              is_surveys,
              department,
              principal: principal || "暂未分配负责人"
            };
          });
        }
      });
    },
    handelsearch() {
      this.loadTableData({
        limit: this.pagination.pageSize,
        title: this.searchText
      });
      this.searchText = "";
    },
    deleteRecord(key) {
      this.dataSource = this.dataSource.filter((item) => item.key !== key);
      this.selectedRows = this.selectedRows.filter((item) => item.key !== key);
    },
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    onClear() {
      this.$message.info("您清空了勾选的所有行");
    },
    onStatusTitleClick() {
      this.$message.info("你点击了状态栏表头");
    },
    onChange(e) {
      console.log(e);
      const { current, pageSize } = e;
      this.loadTableData({ limit: pageSize, page: current });
    },
    handleMenuClick(e) {
      if (e.key === "delete") {
        this.remove();
      }
    },
    // eslint-disable-next-line no-unused-vars
    cancel(key) {
      // this.$message.info(`点击了取消,行数为${key + 1}行`);
    },
    // 删除确认
    delete_confirm(key) {
      // 发起删除的请求
      deleteItem(key).then((res) => {
        // console.log(res, "delete");
        // 成功
        if (res.data.code === 20000) {
          // 提示信息
          this.$message.success({
            content: res.data.message || "删除成功~"
          });
          // 删除成功后重新获取数据
          const { pageSize, current } = this.pagination;
          this.loadTableData({ limit: pageSize, page: current });
        }
      });
      // this.$message.info(`点击了确定,行数为${key + 1}行`);
      // this.deleteRecord(key);
    },
    // 改变需求状态
    changeStatus(key, requirement_id) {
      // 发起请求
      suspend({ key, requirement_id }).then((res) => {
        // console.log(res, "delete");
        // 成功
        if (res.data.code === 20000) {
          // 提示信息
          this.$message.success({
            content: res.data.message || "修改成功~"
          });
          // 删除成功后重新获取数据
          const { pageSize, current } = this.pagination;
          this.loadTableData({ limit: pageSize, page: current });
        }
      });
    },
    handelStatusChange(status, requirement_id) {
      this.changeStatus(status, requirement_id);
      const { pageSize, current } = this.pagination;
      this.loadTableData({ limit: pageSize, page: current });
    }
  }
};
</script>

<style lang="less">
.search-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;

  > div {
    .search-input input {
      padding-left: 45px !important;
    }
    display: flex;
    width: 60%;
    .ant-input-affix-wrapper {
      display: inline-block;
      width: calc(100% - 150px);
      height: 54px !important;
      input {
        height: 100% !important;
      }
      input::-webkit-input-placeholder {
        color: #9999;
        font-size: 16px;
      }

      input::-moz-placeholder {
        /* Mozilla Firefox 19+ */
        color: #9999;
        font-size: 16px;
      }

      input:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 */
        color: #9999;
        font-size: 16px;
      }
    }
    .search-button {
      margin-left: 30px;
      width: 120px;
      height: 54px;
    }
  }
}
.demand {
  .tabel-wrapper {
    border-radius: 5px;
    // min-height: 450px;
    background-color: #fff;
    color: #1f1f1f;
    // .ant-empty {
    //   // min-height: 450px;
    // }
    .ant-pagination {
      margin-top: 60px !important;
    }
    tr {
      height: 66px !important;
      // padding-left: 10px;
    }
    .ant-table-thead {
      padding-left: 20px;
      background: #effaff;
      & > tr > th {
        background: #effaff !important;
      }
    }
    .ant-table-tbody {
      padding-left: 20px;
    }
    .ant-table-pagination.ant-pagination {
      float: unset !important;
      text-align: center;
    }
  }
}
</style>
